package com.jwsoft.manager.core.dao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.jwsoft.manager.common.enums.EduStatusTypeEnum;
import com.jwsoft.manager.common.vo.eduDataTaskDetail.DataTaskDetailOptionVO;
import com.jwsoft.manager.core.dao.mapper.EduhCompanyMapper;
import com.jwsoft.manager.core.dao.mapper.EdutCompanyMapper;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.mapper.EduCompanyMapper;
import com.jwsoft.manager.core.dao.service.EduCompanyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwsoft.manager.core.dao.service.EduDataTaskDetailService;
import com.jwsoft.manager.core.dao.service.TableService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 法人登记基本信息表服务实现类
 *
 * @author wangtao
 * @since 2022-12-28
 */
@Service
@Slf4j
public class EduCompanyServiceImpl extends ServiceImpl<EduCompanyMapper, EduCompany> implements EduCompanyService, TableService {

    @Autowired
    private EduhCompanyMapper hCompanyMapper;

    @Autowired
    private EdutCompanyMapper tCompanyMapper;

    @Autowired
    private EduDataTaskDetailService detailService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private EduDataTaskDetailService dataTaskDetailService;


    private static final String COMPANY_TABLE = "edu_company";
    //每次处理的数量为1w条数据
    private static final Integer PAGE_SIZE = 10000;
    @Override
    public Integer dataMigration(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduCompanyServiceImpl服务的dataMigration()来进行处理迁移数据");
        Integer count = this.baseMapper.selectCountByYear(optionVO.getYear());
        log.info("edu_company迁移" + count + "条数据");
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        for (int i = 0; i < totalPages; i++) {
            List<EduCompany> companyList = this.baseMapper.selectByYear(optionVO.getYear(),PAGE_SIZE);
            if (companyList.size() > 0) {
                List<EduhCompany> hCompanyList = companyList.stream().map(eduCompany -> {
                    EduhCompany eduhCompany = new EduhCompany();
                    BeanUtils.copyProperties(eduCompany, eduhCompany);
                    eduhCompany.setTaskDetailId(taskDetail.getTaskDetailId());
                    //数据是否已加密，初始状态未加密
                    eduhCompany.setEncryptFlag(BoolEnum.FALSE.getType());
                    eduhCompany.setEncryptStatus(EduStatusTypeEnum.dcl.getType());
                    eduhCompany.setCleanFlag(BoolEnum.FALSE.getType());
                    return eduhCompany;
                }).collect(Collectors.toList());
                try {
                    this.performDataMigration(hCompanyList, companyList.size(), optionVO);
                } catch (Exception e) {
                    log.error("edu_company迁移数据发生异常");
                    throw new RuntimeException("EduCompanyServiceImpl:" + e);
                }
            }
        }
        return count;
    }

    private void performDataMigration(List<EduhCompany> hCompanyList, Integer count, DataTaskDetailOptionVO optionVO) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    int saveHCount = hCompanyMapper.saveBatch(hCompanyList);
                    if (saveHCount != count) {
                        throw new RuntimeException("数据迁移到历史表失败");
                    }
                    //2.数据销毁
                    EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
                    if (ObjectUtils.isEmpty(taskDetail)) {
                        throw new AppException("任务数据不存在，请检查数据是否有误");
                    }
                    Integer deleteCount = baseMapper.deleteByTaskHistory(taskDetail.getTaskDetailId());
                    if (!count.equals(deleteCount)) {
                        throw new RuntimeException("数据删除失败");
                    }
                    log.info("edu_company数据销毁成功！销毁数量：" + count);
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void dataEncryption(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduCompanyServiceImpl服务的dataEncryption()来进行处理数据加密");
        Integer count = 0;
        if (taskDetail.getEncryptCount() == 0) {
            count = this.baseMapper.selectEncryptionCountByYear(optionVO.getYear(), optionVO.getTaskDetailId());
            taskDetail.setEncryptCount(count);
        }
        Boolean errorFlag = false;
        Integer errorCount = 0;
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        // 计算循环次数 = 总页数
        for (int i = 0; i < totalPages; i++) {
            List<EduhCompany> hCompanyList =
                    this.baseMapper.selectEncryptionByYear(optionVO.getYear(), optionVO.getTaskDetailId(), PAGE_SIZE);
            for (EduhCompany eduhCompany : hCompanyList) {
                //加密
                try {
                    this.encrypt(eduhCompany);
                    eduhCompany.setEncryptTime(new Date());
                    eduhCompany.setEncryptStatus(EduStatusTypeEnum.success.getType());
                    eduhCompany.setEncryptRemarks("加密成功");
                    eduhCompany.setEncryptFlag(BoolEnum.TRUE.getType());
                    hCompanyMapper.updateById(eduhCompany);
                } catch (Exception e) {
                    //解密
                    this.decrypt(eduhCompany);
                    eduhCompany.setEncryptTime(new Date());
                    eduhCompany.setEncryptStatus(EduStatusTypeEnum.error.getType());
                    eduhCompany.setEncryptFlag(BoolEnum.FALSE.getType());
                    eduhCompany.setEncryptRemarks("加密失败"+e.getMessage());
                    hCompanyMapper.updateById(eduhCompany);
                    errorFlag = true;
                    errorCount++;
                    throw new AppException(e);
                }
            }
        }
        if (!errorFlag) {
            //无异常，返回任务状态
            taskDetail.setEncryptStatus(EduStatusTypeEnum.success.getType());
            taskDetail.setEncryptRemarks("加密成功");
            taskDetail.setEncryptTime(new Date());
        } else {
            taskDetail.setEncryptStatus(EduStatusTypeEnum.error.getType());
            taskDetail.setEncryptTime(new Date());
            taskDetail.setEncryptRemarks(taskDetail.getHandleTable()
                    +"加密失败,加密出错的数据：" + errorCount);
        }
        detailService.updateById(taskDetail);
    }

    private void decrypt(EduhCompany eduhCompany) {
        if (StringUtils.isNotBlank(eduhCompany.getTyxydm())){
            eduhCompany.setTyxydm(CommonSecureUtil.sm4Decrypt(eduhCompany.getTyxydm()));
        }
        if (StringUtils.isNotBlank(eduhCompany.getDh())){
            eduhCompany.setDh(CommonSecureUtil.sm4Decrypt(eduhCompany.getDh()));
        }
        if (StringUtils.isNotBlank(eduhCompany.getFrmc())){
            eduhCompany.setFrmc(CommonSecureUtil.sm4Decrypt(eduhCompany.getFrmc()));
        }
        if (StringUtils.isNotBlank(eduhCompany.getFrZjhm())){
            eduhCompany.setFrZjhm(CommonSecureUtil.sm4Decrypt(eduhCompany.getFrZjhm()));
        }
    }

    private void encrypt(EduhCompany eduhCompany) {
        if (StringUtils.isNotBlank(eduhCompany.getTyxydm())){
            eduhCompany.setTyxydm(CommonSecureUtil.sm4Encrypt(eduhCompany.getTyxydm()));
        }
        if (StringUtils.isNotBlank(eduhCompany.getDh())){
            eduhCompany.setDh(CommonSecureUtil.sm4Encrypt(eduhCompany.getDh()));
        }
        if (StringUtils.isNotBlank(eduhCompany.getFrmc())){
            eduhCompany.setFrmc(CommonSecureUtil.sm4Encrypt(eduhCompany.getFrmc()));
        }
        if (StringUtils.isNotBlank(eduhCompany.getFrZjhm())){
            eduhCompany.setFrZjhm(CommonSecureUtil.sm4Encrypt(eduhCompany.getFrZjhm()));
        }
    }

    @Override
    public Integer dataDestruction(DataTaskDetailOptionVO optionVO) {
        EduDataTaskDetail taskDetail = detailService.getById(optionVO.getTaskDetailId());
        log.info("调用了EduCompanyServiceImpl服务的dataDestruction来进行处理数据清洗");
        //企业数据销毁规则：2022年全部保留  2023年保留company_id的企业数据

        //判断是否为2023年之前的数据
        if (taskDetail.getYear() < 2023){
            return 0;
        }
        //判断指定年份的报名数据是否执行过迁移
        Boolean queryHistory =
                dataTaskDetailService.verifyQueryHistory(optionVO.getYear(), COMPANY_TABLE);
        List<EduhCompany> hCompanies = new ArrayList<>();
       if (queryHistory){
           //从历史报名数据查询
           hCompanies = this.baseMapper.queryHistoryCleanCompanyWithEnroll
                   (taskDetail.getYear(),taskDetail.getTaskDetailId());
       }else{
           hCompanies = this.baseMapper.queryCleanCompanyWithEnroll
                   (taskDetail.getYear(),taskDetail.getTaskDetailId());
       }
        Integer cleanCount = hCompanies.size();
       if (cleanCount != 0){
           try {
               this.preformDataClean(hCompanies,cleanCount);
           } catch (Exception e) {
               log.error("eduh_company数据清洗发生异常");
               throw new RuntimeException("EduCompanyServiceImpl:" + e);
           }
       }
        return cleanCount;
    }

    private void preformDataClean(List<EduhCompany> hCompanies, Integer cleanCount) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    List<EdutCompany> tCompanyList = hCompanies.stream().map(item -> {
                        EdutCompany edutCompany = new EdutCompany();
                        BeanUtils.copyProperties(item, edutCompany);
                        edutCompany.setCleanFlag(BoolEnum.TRUE.getType());
                        return edutCompany;
                    }).collect(Collectors.toList());
                    tCompanyMapper.saveBatch(tCompanyList);
                    Integer count = 0;
                    for (EduhCompany hCompany : hCompanies) {
                        count ++;
                        hCompanyMapper.deleteHistoryById(hCompany.getCompanyId());
                    }
                    if (count != cleanCount){
                        throw new AppException("要清洗的数据为："+cleanCount+",清洗的数据为："+count+"数据量不一致，请检查后重试！");
                    }
                } catch (Exception e) {
                    status.setRollbackOnly();
                    throw e;
                }
            }
        });
    }

    @Override
    public void tempDataDestruction() {
        System.out.println("空闲数据销毁");
    }

    @Override
    public void dataDecrypt(DataTaskDetailOptionVO optionVO) {
        Integer count = Math.toIntExact(hCompanyMapper.selectCount(new QueryWrapper<EduhCompany>().lambda().eq(EduhCompany::getTaskDetailId, optionVO.getTaskDetailId())));
        // 计算总页数
        int totalPages = (count % PAGE_SIZE == 0) ? (count / PAGE_SIZE) : (count / PAGE_SIZE + 1);
        int currentPage = 0;
        for (int i = 0; i < totalPages; i++) {
            List<EduhCompany> eduhCompanyList =
                    hCompanyMapper.selectByTaskDetailId(optionVO.getTaskDetailId(),currentPage,PAGE_SIZE);

            List<EdutCompany> tCompany = eduhCompanyList.stream().map(item -> {
                if (BoolEnum.TRUE.getType().equalsIgnoreCase(item.getEncryptFlag())) {
                    //需要进行解密
                    this.decrypt(item);
                }
                EdutCompany edutCompany = new EdutCompany();
                BeanUtils.copyProperties(item, edutCompany);
                return edutCompany;
            }).collect(Collectors.toList());
            tCompanyMapper.saveBatch(tCompany);
            currentPage ++;
        }
    }
}
